#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>

#include "nweb.h"
#include "nweb_log.h"
#include "http_response.h"

/* Resource Handler */
void handle_resource(request_rec* r) {
    int j, file_fd;
    long ret;
    
    /* open the file for reading */
    if(( file_fd = open(&r->uri[1],O_RDONLY)) == -1)
            nweb_log(SORRY, "failed to open file",r->uri,r->fd);

    nweb_log(LOG,"SEND",r->uri,r->hit);

    /* response HTTP OK to the browser */
    (void)sprintf(r->buffer,"HTTP/1.0 200 OK\r\nContent-Type: %s\r\n\r\n", r->fstr);
    (void)write(r->fd,r->buffer,strlen(r->buffer));

    /* send file back to the web browser
     * send file in 8KB block - last block may be smaller 
     */
    while (	(ret = read(file_fd, r->buffer, BUFSIZE)) > 0 ) {
            (void)write(r->fd,r->buffer,ret);
    }
}
